
<div class="standardContainer">
    <div class="ui basic segment">
      <h2>Redirection Rules</h2>
      <p>Add exception case for redirecting any matching URLs</p>
    </div>
    <!-- Current list of redirection rules-->
    <div style="width: 100%; overflow-x: auto;">
        <table class="ui sortable unstackable celled table" >
          <thead>
              <tr>
                  <th>Redirection URL</th>
                  <th>Destination URL</th>
                  <th class="no-sort">Copy Pathname</th>
                  <th class="no-sort">Status Code</th>
                  <th class="no-sort">Actions</th>
              </tr>
          </thead>
          <tbody id="redirectionRuleList">
              <tr>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
              </tr>
          </tbody>
      </table>
    </div>
    <div class="ui green message" id="delRuleSucc" style="display:none;">
      <i class="ui green checkmark icon"></i> Redirection Rule Deleted
    </div>
    <!-- Options -->
    <div class="ui basic segment advanceoptions">
      <div class="ui accordion advanceSettings">
          <div class="title">
            <i class="dropdown icon"></i>
              Advance Settings
          </div>
          <div class="content">
            <div class="ui basic segment">
              <div class="ui toggle checkbox">
                  <input id="redirectRegex" type="checkbox">
                  <label>Enable Regular Expression Support<br>
                  <small>Regular expression redirection check will noticeably slow down page load<br>
                    Support <a href="https://yourbasic.org/golang/regexp-cheat-sheet/" target="_blank">Go style regex</a>. e.g. <code style="background-color: rgb(44, 44, 44); color: white">.\.redirect\.example\.com</code></small></label>
              </div>
            </div>
          </div>
      </div>
    </div>

    <!-- Add New Redirection Rules -->
    <div class="ui divider"></div>
    <h4>Add Redirection Rule</h4>
    <div class="ui form">
        <div class="field">
          <label>Redirection URL (From)</label>
          <input type="text" id="rurl" name="redirection-url" placeholder="Redirection URL">
          <small><i class="ui circle info icon"></i> Any matching prefix of the request URL will be redirected to the destination URL, e.g. redirect.example.com</small>
        </div>
        <div class="field">
          <label>Destination URL (To)</label>
          <input type="text" name="destination-url" placeholder="Destination URL">
          <small><i class="ui circle info icon"></i> The target URL request being redirected to, e.g. dest.example.com/mysite/ or dest.example.com/script.php, <b>sometime you might need to add tailing slash (/) to your URL depending on your use cases</b></small>
        </div>
        <div class="field">
          <div class="ui checkbox">
            <input type="checkbox" name="forward-childpath" tabindex="0" class="hidden" checked>
            <label>Forward Pathname</label>
          </div>
          <div class="ui message">
            <p>Append the current pathname after the redirect destination</p>
            <i class="check square outline icon"></i> old.example.com<b>/blog?post=13</b> <i class="long arrow alternate right icon" style="margin-left: 1em;"></i> new.example.com<b>/blog?post=13</b> <br>
            <i class="square outline icon"></i> old.example.com<b>/blog?post=13</b> <i class="long arrow alternate right icon" style="margin-left: 1em;"></i> new.example.com
          </div>
        </div>
        <div class="grouped fields">
            <label>Redirection Status Code</label>
            <div class="field">
              <div class="ui radio checkbox">
                <input type="radio" name="redirect-type" value="307" checked>
                <label>Temporary Redirect <br><small>Status Code: 307</small></label>
              </div>
            </div>
            <div class="field">
              <div class="ui radio checkbox">
                <input type="radio" name="redirect-type" value="301">
                <label>Moved Permanently <br><small>Status Code: 301</small></label>
              </div>
            </div>
        </div>
        <button class="ui basic button" onclick="addRules();"><i class="ui teal plus icon"></i> Add Redirection Rule</button>
        <div class="ui green message" id="ruleAddSucc" style="display:none;">
          <i class="ui green checkmark icon"></i> Redirection Rules Added
        </div>
        <br><br>
    </div>
  </div>
</div>
<script>
    /*
      Redirection functions
    */

    $(".checkbox").checkbox();
    $(".advanceSettings").accordion();
    function resetForm() {
      document.getElementById("rurl").value = "";
      document.getElementsByName("destination-url")[0].value = "";
      document.getElementsByName("forward-childpath")[0].checked = true;
    }

    function addRules(){
        let redirectUrl = document.querySelector('input[name="redirection-url"]').value;
        let destUrl = document.querySelector('input[name="destination-url"]').value;
        let forwardChildpath = document.querySelector('input[name="forward-childpath"]').checked;
        let redirectType = document.querySelector('input[name="redirect-type"]:checked').value;

        $.cjax({
            url: "/api/redirect/add", 
            method: "POST",
            data: {
                redirectUrl: redirectUrl,
                destUrl: destUrl,
                forwardChildpath: forwardChildpath,
                redirectType: parseInt(redirectType),
            },
            success: function(data){
                if (data.error != undefined){
                  alert(data.error);
                }else{
                  $("#ruleAddSucc").stop().finish().slideDown("fast").delay(3000).slideUp("fast");
                }
                initRedirectionRuleList();
                resetForm();
            }
        });
    }

    function deleteRule(obj){
      let targetURL = $(obj).attr("rurl");
      targetURL = JSON.parse(decodeURIComponent(targetURL));
      if (confirm("Confirm remove redirection from " + targetURL + " ?")){
        $.cjax({
              url: "/api/redirect/delete", 
              method: "POST",
              data: {
                  redirectUrl: targetURL,
              },
              success: function(data){
                  if (data.error != undefined){
                    alert(data.error);
                  }else{
                    $("#delRuleSucc").stop().finish().slideDown("fast").delay(3000).slideUp("fast");
                  }
                  initRedirectionRuleList();
              }
          });
        }
    }

    function initRedirectionRuleList(){
        $("#redirectionRuleList").html("");
        $.get("/api/redirect/list", function(data){
            data.forEach(function(entry){
              let encodedEntry = encodeURIComponent(JSON.stringify(entry));
              let hrefURL = entry.RedirectURL;
              if (!hrefURL.startsWith("http")){
                hrefURL = "https://" + hrefURL;
              }
              $("#redirectionRuleList").append(`<tr>
                  <td><a href="${hrefURL}" target="_blank">${entry.RedirectURL}</a></td>
                  <td>${entry.TargetURL}</td>
                  <td>${entry.ForwardChildpath?"<i class='ui green checkmark icon'></i>":"<i class='ui red remove icon'></i>"}</td>
                  <td>${entry.StatusCode==307?"Temporary Redirect (307)":"Moved Permanently (301)"}</td>
                  <td>
                    <button onclick="editRule(this);" payload="${encodedEntry}" title="Edit redirection rule" class="ui mini circular icon basic button redirectEditBtn"><i class="edit icon"></i></button>
                    <button onclick="deleteRule(this);" rurl="${encodeURIComponent(JSON.stringify(entry.RedirectURL))}" title="Delete redirection rule" class="ui mini red circular icon basic button"><i class="trash icon"></i></button>
                  </td>
              </tr>`);
            });
            
            if (data.length == 0){
              $("#redirectionRuleList").append(`<tr><td colspan="5"><i class="green check circle icon"></i> No redirection rule</td></tr>`);
            }
            
        });
    }
    initRedirectionRuleList();

    function editRule(obj){
      $(".redirectEditBtn").addClass("disabled");
      let payload = JSON.parse(decodeURIComponent($(obj).attr("payload")));
      let row = $(obj).closest("tr");
      let redirectUrl = payload.RedirectURL;
      let destUrl = payload.TargetURL;
      let forwardChildpath = payload.ForwardChildpath;
      let statusCode = payload.StatusCode;

      row.html(`
        <td>
          <div class="ui small input">
            <input type="text" value="${redirectUrl}" id="editRedirectUrl">
          </div>
        </td>
        <td>
          <div class="ui small input">
            <input type="text" value="${destUrl}" id="editDestUrl">
          </div>
        </td>
        <td><div class="ui toggle checkbox"><input type="checkbox" ${forwardChildpath ? "checked" : ""} id="editForwardChildpath"><label></label></div></td>
        <td>
          <div class="ui radio checkbox"><input type="radio" name="editStatusCode" value="307" ${statusCode == 307 ? "checked" : ""}><label>Temporary Redirect (307)</label></div><br>
          <div class="ui radio checkbox"><input type="radio" name="editStatusCode" value="301" ${statusCode == 301 ? "checked" : ""}><label>Moved Permanently (301)</label></div>
        </td>
        <td>
          <button onclick="saveEditRule(this);" payload="${encodeURIComponent(JSON.stringify(payload))}" class="ui small circular green icon basic button"><i class="save icon"></i></button>
          <button onclick="initRedirectionRuleList();" class="ui small circular icon basic button"><i class="cancel icon"></i></button>
        </td>
      `);

      $(".checkbox").checkbox();
    }

    function saveEditRule(obj){
      let payload = JSON.parse(decodeURIComponent($(obj).attr("payload")));
      let redirectUrl = $("#editRedirectUrl").val();
      let destUrl = $("#editDestUrl").val();
      let forwardChildpath = $("#editForwardChildpath").is(":checked");
      let statusCode = parseInt($("input[name='editStatusCode']:checked").val());

      $.cjax({
        url: "/api/redirect/edit", 
        method: "POST",
        data: {
            originalRedirectUrl: payload.RedirectURL,
            newRedirectUrl: redirectUrl,
            destUrl: destUrl,
            forwardChildpath: forwardChildpath,
            redirectType: statusCode,
        },
        success: function(data){
            if (data.error != undefined){
              msgbox(data.error, false);
            }else{
              msgbox("Redirection rule updated", true);
              initRedirectionRuleList();
            }
        }
      });
    }

    function initRegexpSupportToggle(){
      $.get("/api/redirect/regex", function(data){
        //Set the checkbox initial state
        if (data == true){
          $("#redirectRegex").parent().checkbox("set checked");
        }else{
          $("#redirectRegex").parent().checkbox("set unchecked");
        }

        //Bind event to the checkbox
        $("#redirectRegex").on("change", function(){
          $.cjax({
            url: "/api/redirect/regex",
            method: "POST",
            data: {"enable": $(this)[0].checked},
            success: function(data){
              if (data.error != undefined){
                msgbox(data.error, false);
              }else{
                msgbox("Regex redirect setting updated", true);
              }
            }
          });
        });
      });
    }

    initRegexpSupportToggle();

    $("#rurl").on('change', (event) => {
      const value = event.target.value.trim().replace(/^(https?:\/\/)/, '');
      event.target.value = value;
    });
    
</script>